<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        style="display: none;"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['id']"/>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="选择模板"
      >
        <a-switch id="search" checkedChildren="是" unCheckedChildren="否"
                  v-model="search"/>
      </a-form-item>

      <a-form-item
        label="操作人"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        has-feedback
      >
        <a-select placeholder="请选择操作人" mode="combobox" allow-clear
                  v-decorator="['owner', {rules: [{required: true, message: '请选择操作人！'}]}]">
          <a-select-option v-for="item in ownerList" :key="item" :value="item">{{ item
            }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="模板类型"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-row :gutter="20">
          <a-col :md="15" :sm="24">
            <a-tree-select
              v-decorator="['channel', {rules: [{ required: true, message: '请选择渠道！' }]}]"
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
              :treeData="ChannelTree"
              placeholder="请选择渠道"
              treeDefaultExpandAll
            >
                  <span slot="title" slot-scope="{ id }">{{ id }}
                  </span>
            </a-tree-select>
          </a-col>
          <a-col :md="9" :sm="24">
            <a-select placeholder="请选择操作类型" mode="combobox" allow-clear
                      v-decorator="['type', {rules: [{required: true, message: '请选择操作类型！'}]}]" @change="getTemplate">
              <a-select-option v-for="item in taskTypeList" :key="item" :value="item">{{ item
                }}
              </a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item
        label="日期时间"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        has-feedback
      >
        <a-date-picker
          style="width:100%"
          show-time
          placeholder="请选择日期时间"
          format="YYYY-MM-DD HH:mm"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          v-decorator="['date_time', {rules: [{required: true, message: '请选择日期时间！'}]}]"
        >
        </a-date-picker>
      </a-form-item>
      <a-form-item
        label="标题"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input placeholder="请输入标题" v-decorator="['title', {rules: [{required: true, message: '请输入标题！'}]}]"/>
      </a-form-item>
      <a-form-item
        label="内容"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-textarea placeholder="请输入内容" v-decorator="['content']" :auto-size="{ minRows: 3 }"/>
      </a-form-item>
      <div v-show="versionShow">
        <a-form-item
          label="版本"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >

          <a-select
            show-search
            allow-clear
            mode="combobox"
            v-decorator="['version', {rules: [{required: versionRequired, message: '请输入版本！'}]}]"
            placeholder="请选择版本..."
            @focus="fetchVersion">
            <a-select-option v-for="item in versionList" :key="item">
              {{ item }}
            </a-select-option>
          </a-select>

        </a-form-item>
      </div>
      <a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="保存为模板"
        >
          <a-switch id="template" checkedChildren="是" unCheckedChildren="否"
                    v-decorator="['template', { valuePropName: 'checked' }]"/>
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
  import { getProjectTree } from '@/api/main/project'
  import * as api from '@/api/system/task'
  import moment from 'moment'
  // 导入提示信息字典
  import config from '@/config/dict'

  const taskTypeList = ['更新', '合服', '其他']
  export default {
    name: 'sForm',
    data() {
      return {
        labelCol: {
          xs: { span: 10 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        title: '',
        confirmLoading: true,
        search: false,
        ChannelTree: [],
        taskTypeList,
        ownerList: [],
        versionList: [],
        versionShow: true,
        versionRequired: true,
        form: this.$form.createForm(this)
      }
    },
    methods: {
      // 初始化方法
      open(record, type) {
        this.visible = true
        if (record) {
          this.title = '编辑排期'
        } else {
          this.title = '新增排期'
          this.form.getFieldDecorator('template', { initialValue: true })
        }
        if (record) {
          setTimeout(() => {
            this.setFormItem(record, type)
          }, 100)
        }
        this.getOwnerList()
        this.getProjectTree()
      },
      setFormItem(record, type) {
        this.form.setFieldsValue(
          {
            owner: record.owner,
            channel: record.channel,
            type: record.type,
            date_time: moment(record.date_time),
            title: record.title,
            content: record.content,
            version: record.version,
            template: record.template
          }
        )
        if (!type) {
          this.form.setFieldsValue(
            {
              id: record.id
            }
          )
        } else {
          this.title = '克隆排期'
        }
        this.choiceType(record.type)
      },
      /**
       * 获取渠道树
       */
      getProjectTree() {
        getProjectTree().then(res => {
          if (res.success) {
            this.ChannelTree = res.data.rows
            this.confirmLoading = false
          }
        })
      },
      /**
       * 获取操作人list
       */
      getOwnerList() {
        api.getOwnerList().then(res => {
          if (res.success) {
            this.ownerList = res.data
          }
        })
      },
      /**
       * 排期类型变化
       */
      choiceType(value) {
        if (value === '合服' || value === '其他') {
          this.versionShow = false
          this.versionRequired = false
        } else {
          this.versionShow = true
          this.versionRequired = true
        }
      },
      /**
       * 搜索排期模板
       */
      getTemplate(value) {
        this.choiceType(value)
        if (this.form.getFieldValue('channel')) {
          if (this.search) {
            const params = {
              channel: this.form.getFieldValue('channel'),
              type: value
            }
            // 发送查找模板请求
            api.getTemplate(params).then(res => {
              if (res.success) {
                this.setFormItem(res.data)
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      },
      fetchVersion() {
        let params = {
          'channel': this.form.getFieldValue('channel')
        }
        getVersionList(params).then(res => {
          this.versionList = res.data
        })
      },
      // [确认按钮]提交数据方法
      // handleSubmit() {
      //   const { form: { validateFields } } = this
      //   this.confirmLoading = true
      //   validateFields((errors, values) => {
      //     this.message = config.msgDict[0]
      //     if (values.id) {
      //       this.message = config.msgDict[1]
      //     }
      //     values.date_time = moment(values.date_time).format('YYYY-MM-DD HH:mm:ss')
      //     if (!errors) {
      //       this.confirmLoading = false
      //       api.addObj(values).then((res) => {
      //         if (res.success) {
      //           this.$message.success(this.message['success'])
      //           this.handleCancel()
      //           this.$emit('ok', values)
      //         } else {
      //           this.$message.error(this.message['failed'] + res.message)
      //         }
      //       }).finally((res) => {
      //         this.confirmLoading = false
      //       })
      //     } else {
      //       this.confirmLoading = false
      //     }
      //   })
      // },
      handleSubmit() {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
            if (!errors) {
              values.date_time = moment(values.date_time).format('YYYY-MM-DD HH:mm:ss')
              if (values.id) {
                this.message = config.msgDict[1]
                api.updateObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              } else {
                this.message = config.msgDict[0]
                api.addObj(values)
                  .then((res) => {
                    this._handle_response(res, values)
                  })
              }
            }
          }
        )
      },
      // 处理返回消息
      _handle_response(res, values) {
        if (!res.error) {
          this.$message.success(this.message['success'])
          this.handleCancel()
          this.$emit('ok', values)
        } else {
          this.$message.error(this.message['failed'] + res.error)
        }
      },
      // [取消按钮]重置数据,关闭弹框
      handleCancel() {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
